<template>
	<el-card class="layout-query">
		<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="search()">
			<el-form-item label="实施日期">
				<el-date-picker
					v-model="state.date"
					type="daterange"
					value-format="YYYY-MM-DD"
					format="YYYY-MM-DD"
					nge-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					clearable
				/>
			</el-form-item>
			<el-form-item label="标准名称/编号">
				<el-input v-model="state.queryForm.standardNameOrNumber" placeholder="请输入" clearable />
			</el-form-item>
			<el-form-item label="主参编单位">
				<el-input v-model="state.queryForm.mainEditorUnitName" placeholder="请输入" clearable />
			</el-form-item>
			<el-form-item label="发布状态">
				<el-select v-model="state.queryForm.hasPublic" placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in publishStatus" :key="item.id" :label="item.name" :value="item.code"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="search()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset()">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>
	<el-card>
		<el-space style="width: 100%; justify-content: flex-end">
			<el-space v-auth="'M006_1_Output'">
				<el-button type="primary" @click="exportHandle">导出</el-button>
			</el-space>
			<el-space v-auth="'M006_1_A'">
				<el-button type="primary" @click="handleAdd">新增</el-button>
			</el-space>
			<el-space v-auth="'M006_1_Input'">
				<el-button type="primary" @click="downLoadTemplate">模板下载</el-button>
			</el-space>
			<el-space v-auth="'M006_1_Input'">
				<!-- <el-button type="primary">文件导入</el-button> -->
				<el-upload
					:action="uploadApi"
					:headers="uploadHeaders"
					accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
					:on-success="handleImportSuccess"
					:show-file-list="false"
					:on-error="handleImportError"
				>
					<el-button type="primary">文件导入</el-button>
				</el-upload>
			</el-space>
		</el-space>
		<el-table v-loading="state.dataListLoading" :data="state.dataList" stripe class="layout-table" @selection-change="selectionChangeHandle">
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
			<el-table-column prop="standardName" label="标准名称" header-align="center" align="center"></el-table-column>
			<el-table-column prop="standardEnName" label="标准名称(英)" header-align="center" align="center"></el-table-column>
			<el-table-column prop="standardNumber" label="标准编号" header-align="center" align="center"></el-table-column>
			<el-table-column prop="mainEditorUnitName" label="主编单位" header-align="center" align="center"></el-table-column>
			<el-table-column prop="publishTime" label="发布日期" header-align="center" align="center"></el-table-column>
			<el-table-column prop="implementTime" label="实施日期" header-align="center" align="center"></el-table-column>
			<el-table-column label="发布状态" align="center" prop="publishStatus" width="100">
				<template #default="scope">
					<span>{{ scope.row.publishStatus }}</span>
				</template>
			</el-table-column>

			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="100">
				<template #default="scope">
					<el-icon v-auth="'M006_1_U'" :size="16" color="#1491FF" title="编辑" style="cursor: pointer; margin: 0 6px" @click="handleEdit(scope.row)">
						<Edit />
					</el-icon>
					<el-icon
						v-auth="'M006_1_D'"
						:size="16"
						color="#fe6360"
						title="删除"
						style="cursor: pointer; margin: 0 6px"
						@click="deleteBatchHandle(scope.row.id)"
					>
						<Delete />
					</el-icon>
					<el-icon
						v-if="scope.row.publishStatus == '未发布'"
						:size="16"
						color="#1491FF"
						title="发布"
						style="cursor: pointer; margin: 0 6px"
						@click="handleSend(scope.row.id)"
					>
						<CircleCheck />
					</el-icon>

					<el-icon
						v-if="scope.row.publishStatus == '已发布'"
						:size="16"
						color="#1491FF"
						title="取消发布"
						style="cursor: pointer; margin: 0 6px"
						@click="handleCancel(scope.row.id)"
					>
						<CircleClose />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.pageNum"
			:page-size="state.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>

		<!-- 弹窗, 新增 / 修改 -->
		<!-- <updateDialog v-model="showAddDialog"  @refresh-data-list="getDataList"></updateDialog> -->
		<addDialog v-model="showAddDialog" :edit-id="editId" :project-id="projectId" @submit-success="addSuccess"></addDialog>
	</el-card>
</template>
<script setup lang="ts">
import { cancelPublishApi, publishApi, standardSystemDeletepi, standardSystemListApi } from '@/api/standard/maintenance/index'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'
import addDialog from './components/addDialog.vue'
const userStore = useUserStore()
const dictionaryStore = useDictionaryStore()
const publishStatus = dictionaryStore.getDictionaryByCode('T0032')

const updateDialogRef = ref()
const showAddDialog = ref<boolean>(false)
const state = reactive({
	dataListUrl: '/sys/post/page',
	deleteUrl: '/sys/post',
	queryForm: {
		startImplementTime: '',
		endImplementTime: '',
		standardNameOrNumber: '',
		mainEditorUnitName: '',
		hasPublic: ''
	},
	date: [],
	pageNum: 1,
	pageSize: 10,
	total: 1,
	dataListLoading: false,
	isUpdateFlag: false,
	dataList: []
})
const editId = ref<string>('')
const projectId = ref<string>('')

const uploadApi = window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/standardSystem/importExcel'
const uploadHeaders = {
	Authorization: userStore.token
}

watch(
	() => showAddDialog.value,
	newVal => {
		if (newVal == false) {
			editId.value = ''
			projectId.value = ''
		}
	}
)

const handleCancel = (id: Number | String) => {
	ElMessageBox.confirm('确定取消发布吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		cancelPublishApi(id).then(res => {
			ElMessage({
				type: 'success',
				message: '取消发布成功'
			})
			getDataList()
		})
	})
}
const handleSend = (id: Number | String) => {
	ElMessageBox.confirm('确定发布吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		publishApi(id).then(res => {
			ElMessage({
				type: 'success',
				message: '发布成功'
			})
			getDataList()
		})
	})
}
// 新增编辑
const handleUpdateRecord = (isUpdate: Boolean, row: any) => {
	updateDialogRef.value.init(isUpdate, row)
}

const getDataList = async () => {
	if (state.date && state.date.length > 0) {
		state.queryForm.startImplementTime = state.date[0]
		state.queryForm.endImplementTime = state.date[1]
	}
	state.dataListLoading = true
	await standardSystemListApi({
		pageNum: state.pageNum,
		pageSize: state.pageSize,
		...state.queryForm
	}).then(res => {
		state.dataListLoading = false
		state.dataList = res.data.list || []
		state.total = res.data.total || 0
	})
}
const delMethods = async (id: String | Number) => {
	await standardSystemDeletepi({ id: id }).then(res => {
		ElMessage.success('删除成功')
		reset()
	})
}

const search = () => {
	state.pageNum = 1
	getDataList()
}

const reset = () => {
	state.date = []
	state.queryForm = {
		startImplementTime: '',
		endImplementTime: '',
		standardNameOrNumber: '',
		mainEditorUnitName: '',
		hasPublic: ''
	}
	state.pageNum = 1
	getDataList()
}

// 删除
const deleteBatchHandle = (id: String | Number) => {
	ElMessageBox.confirm('是否删除?', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			delMethods(id)
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败'
			})
		})
}

const addSuccess = (e: any) => {
	reset()
}
const selectionChangeHandle = () => {}
const sizeChangeHandle = (e: number) => {
	state.pageSize = e
	state.pageNum = 1
	getDataList()
}
const currentChangeHandle = (e: number) => {
	state.pageNum = e
	getDataList()
}
const getDataListParent = () => {}
onMounted(() => {
	reset()
	dictionaryStore.initCategory()
})

const handleAdd = async () => {
	showAddDialog.value = true
	editId.value = ''
}

const handleEdit = async (row: any) => {
	editId.value = row.id
	projectId.value = row.projectInfoId
	showAddDialog.value = true
}

const handleImportSuccess = (res: any) => {
	reset()
}

const handleImportError = (err: any) => {
	ElMessage.error('导入失败')
}

const downLoadTemplate = () => {
	try {
		const param = {
			fileName: '标准文件模板'
		}
		axios({
			method: 'post',
			url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/api/scientificResearchInfo/downloadByFileName',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				Authorization: userStore.token
			},
			data: param,
			responseType: 'blob'
		})
			.then(response => {
				ElMessage.success('操作成功，文件已开始下载')
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				})
				const url = window.URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = `标准文件模板.xlsx`
				a.click()
				window.URL.revokeObjectURL(url)
			})
			.catch(error => {
				console.error('导出失败:', error)
			})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const exportHandle = () => {
	try {
		axios({
			method: 'get',
			url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/standardSystem/exportExcel',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				Authorization: userStore.token
			},
			responseType: 'blob'
		})
			.then(response => {
				ElMessage.success('操作成功，文件已开始下载')
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				})
				const url = window.URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = '工程建设标准体系导出.xlsx'
				a.click()
				window.URL.revokeObjectURL(url)
			})
			.catch(error => {
				console.error('导出失败:', error)
			})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}
</script>
